package aash.wowarmory.web;

import aash.utils.net.Connection;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Locale;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Class summarizing the actions around World Of Warcraft armory.
 * @author Aashintan
 */
public class Armory {
    /**
     * getting URL for character information.
     */
    private static String characterUrl = "http://eu.wowarmory.com/character-sheet.xml?r=%1$s&n=%2$s";
    /**
     * getting URL for item information.
     */
    private static String itemUrl = "http://eu.wowarmory.com/item-info.xml?i=%1$s";
    /**
     * Logger.
     */
    private static Logger log = Logger.getLogger(Armory.class.getName());

    /**
     * Class constructor.
     */
    public Armory() {
    }

    /**
     * Return informations of the character.
     * @param stRealm the realm of the character
     * @param stName the name of the character
     * @return xmlDocument
     */
    public static Document getCharacterInformation(final String stRealm, final String stName) {
        return Armory.getInformation(String.format(Armory.characterUrl, stRealm.replace(" ", "+"), stName));
    }

    /**
     * Return informations of the item.
     * @param stId the id of the item
     * @return xmlDocument
     */
    public static Document getItemInformation(final String stId) {
        return Armory.getInformation(String.format(Armory.itemUrl, stId));
    }

    /**
     * Get informations of the page targeted by URL.
     * @param url which we want the source code
     * @return the XML document containing the source code
     */
    private static Document getInformation(final String url) {
        Document xmlDocument = null;
        if (url != null) {
            Connection conn = Connection.getInstance();
            String info = conn.getSourceCode(url, "Mozilla", Locale.FRANCE);
            if (info != null) {
                SAXBuilder sxb = new SAXBuilder();
                try {
                    xmlDocument = sxb.build(new ByteArrayInputStream(info.getBytes()));
                } catch (JDOMException e) {
                    log.error("Error parsing XML document\n" + e);
                } catch (IOException e) {
                    log.error("Error parsing XML document\n" + e);
                }
            }
        }
        return xmlDocument;
    }
}
